using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using Aliyun.OSS;
using Aliyun.OSS.Common;

public class AliyunOssHelper
{
    private static string endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static string accessKeyId = "LTAI5tAshPWcmWSTwrPu9bYS";
    private static string accessKeySecret = "BlDO54Pq3Y16Nj55YqT3wlUmuZNYlf";
    private static string bucketName = "mojuetang-app";
    private static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

    public static void Test()
    {
        string path = "DEV-APP-RESOURCE/3.0.0/Android/1/";
        Debug.Log(ListRemoteFiles(path).Count);
        // DownloadFile(path, "E:/lpf/");
    }

    public static bool CheckDirPathExist(string path)
    {
        return ListRemoteFiles(path).Count != 0;
    }

    public static PutObjectResult UploadFile(string localPath, string remotePath)
    {
        return client.PutObject(bucketName, remotePath, localPath);
    }

    public static DeleteObjectResult DeleteFile(string path)
    {
        return client.DeleteObject(bucketName, path);
    }

    public static List<OssObjectSummary> ListRemoteFiles(string path)
    {
        var listObjectsRequest = new ListObjectsRequest(bucketName);
        // 简单列举Bucket中的文件，默认返回100条记录。
        var result = client.ListObjects(bucketName, path);
        return result.ObjectSummaries.ToList();
    }

    public static bool DownloadFile(string remotePath, string localDirPath)
    {
        try
        {
            var request = new GetObjectRequest(bucketName, remotePath);
            var obj = client.GetObject(request);
            string localPath = $"{localDirPath}{Path.GetFileName(obj.Key)}";
            using (var requestStream = obj.Content)
            {
                byte[] buf = new byte[1024];
                var fs = File.Open(localPath, FileMode.Create);
                var len = 0;
                // 通过输入流将文件的内容读取到文件或者内存中。
                while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                {
                    fs.Write(buf, 0, len);
                }

                fs.Close();
            }
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }
}